﻿import sys
from PySide6.QtCore import Qt, QSettings, Signal, Slot
from PySide6.QtWidgets import QDialog, QMessageBox, QFileDialog
from PySide6.QtNetwork import QNetworkInterface, QAbstractSocket
from Components.MessageBoxFunc import MessageBoxFunc
from Communicate.HttpServer import HttpServer
from Funcs.Config import Config

 # 导入我们生成的界面
from Forms.HttpServerWindow_UI import Ui_FormHttpServer

class HttpServerWindow(QDialog, Ui_FormHttpServer):
    HttpStarted = Signal()
    HttpStopped = Signal()

    def __init__(self, parent = None):
        super().__init__()

        self.setupUi(self)

        flags = self.windowFlags()
        self.setWindowFlags(flags & ~Qt.WindowContextHelpButtonHint)

        list = QNetworkInterface.allAddresses()
        for address in list:
            if address.protocol() == QAbstractSocket.IPv4Protocol and "127.0.0.1" != address.toString():
                self.comboBox_IP.addItem(address.toString())

        self.__IP = self.comboBox_IP.currentText()
        self.__Port = int(self.lineEdit_Port.text())
        self.__DeviceDisplayName = ""
        self.__HttpServer:HttpServer = None

        self.lineEdit_OtaPath.setText(Config.GetCurrentPath() + "/Http/OTA")
        self.lineEdit_LogPath.setText(Config.GetCurrentPath() + "/Http/Log")

    def __del__(self):
        if (self.__HttpServer is not None):
            self.__HttpServer.StopServer()

    def GetIP(self):
        return self.__IP

    def GetPort(self):
        return self.__Port

    def StartHttpServer(self):
        if None != self.__HttpServer:
            return

        self.okButton.setEnabled(False)

        self.__HttpServer = HttpServer()
        if not self.__HttpServer.StartServer(self.comboBox_IP.currentText(), int(self.lineEdit_Port.text()), self.lineEdit_OtaPath.text(), self.lineEdit_LogPath.text()):
            MessageBoxFunc.ShowMessageBox("初始化HTTP服务", "初始化Http服务失败!", self, QMessageBox.Critical)
            self.SetStatus(False)
        else:
            self.SetStatus(True)

    def SetWindowPort(self, portAdded):
        self.__Port += portAdded
        self.lineEdit_Port.setText(str(self.__Port))

    def SetDeviceName(self, deviceDisplayName):
        self.__DeviceDisplayName = deviceDisplayName

        s = QSettings(Config.ConfigIniPath(), QSettings.IniFormat)
        s.beginGroup("UI")
        s.beginGroup(self.__DeviceDisplayName)
        s.beginGroup("HttpServerWindow")

        needStart = False
        if not s.value("OtaPath") is None:
            self.lineEdit_OtaPath.setText(s.value("OtaPath"))
            needStart = True

        if not s.value("LogPath") is None:
            self.lineEdit_LogPath.setText(s.value("LogPath"))
            needStart = True
            
        s.endGroup()
        s.endGroup()
        s.endGroup()

        if needStart:
            self.StartHttpServer()

    def SetLogServerEnable(self, enable):
        self.label_LogPath.setVisible(enable)
        self.lineEdit_LogPath.setVisible(enable)
        self.pushButton_LogPath.setVisible(enable)
        
    @Slot()
    def on_pushButton_OtaPath_clicked(self):
        dir = QFileDialog.getExistingDirectory(self)
        self.lineEdit_OtaPath.setText(dir)
        
    @Slot()
    def on_pushButton_LogPath_clicked(self):
        dir = QFileDialog.getExistingDirectory(self)
        self.lineEdit_LogPath.setText(dir)
        
    @Slot()
    def on_okButton_clicked(self):
        self.StartHttpServer()
        
    @Slot()
    def on_cancelButton_clicked(self):
        self.SetStatus(False)
        
    @Slot()
    def on_pushButton_Close_clicked(self):
        self.reject()

    def SetStatus(self, is_running):
        if is_running:
            self.__IP = self.comboBox_IP.currentText()
            self.__Port = int(self.lineEdit_Port.text())

            self.comboBox_IP.setEnabled(False)
            self.lineEdit_Port.setEnabled(False)
            self.lineEdit_OtaPath.setEnabled(False)
            self.lineEdit_LogPath.setEnabled(False)
            self.pushButton_OtaPath.setEnabled(False)
            self.pushButton_LogPath.setEnabled(False)

            self.cancelButton.setEnabled(True)

            self.label_Status.setText("已启动")
            self.label_Status.setStyleSheet("color: green;")

            s = QSettings(Config.ConfigIniPath(), QSettings.IniFormat)
            s.beginGroup("UI")
            s.beginGroup(self.__DeviceDisplayName)
            s.beginGroup("HttpServerWindow")
            s.setValue("OtaPath", self.lineEdit_OtaPath.text())
            s.setValue("LogPath", self.lineEdit_LogPath.text())
            s.endGroup()
            s.endGroup()
            s.endGroup()

            self.HttpStarted.emit()
        else:
            self.comboBox_IP.setEnabled(True)
            self.lineEdit_Port.setEnabled(True)
            self.lineEdit_OtaPath.setEnabled(True)
            self.lineEdit_LogPath.setEnabled(True)
            self.pushButton_OtaPath.setEnabled(True)
            self.pushButton_LogPath.setEnabled(True)

            self.cancelButton.setEnabled(False)
            self.okButton.setEnabled(True)

            self.label_Status.setText("未启动")
            self.label_Status.setStyleSheet("color: rgb(171, 171, 171);")

            self.__HttpServer.StopServer()
            del self.__HttpServer
            self.__HttpServer = None

            self.HttpStopped.emit()

    def closeEvent(self, event):
        if (self.__HttpServer is not None):
            self.__HttpServer.StopServer()